<template>
	<view class="jd-search__wrap">
		<view class="jd-search">
			<ui-input
				v-model="value2"
				placeholder="搜索商品名称、链接"
				confirm-type="search"
				@input="onInput"
				@blur="onBlur"
				@confirm="search"
				clearable
				prefix-icon="iconfont icon-sousuo"
			></ui-input>
			<button @tap="search">搜索</button>
		</view>

		<view class="jd-search__mask" v-show="showList">
			<view class="block" v-for="(item, index) in keys" :key="index" @tap="selectRow(item)">{{
				item
			}}</view>
		</view>
	</view>
</template>

<script>
export default {
	props: {
		value: String
	},

	data() {
		return {
			value2: null,
			showList: false,
			keys: []
		};
	},

	watch: {
		value: {
			immediate: true,
			handler(val) {
				this.value2 = val;
			}
		}
	},

	methods: {
		selectRow(e) {
			this.value2 = e;
			this.search();
		},

		onBlur() {
			setTimeout(() => {
				this.showList = false;
			}, 0);
		},

		onInput() {
			this.showList = true;

			this.$service.shopping.goods
				.searchSuggestion({
					keyWord: this.value2
				})
				.then(res => {
					this.keys = res;
				});
		},

		search() {
			let d = this.value2;
			if (this.value2) {
				let keys = uni.getStorageSync('jd-searchKey') || [];

				let index = keys.indexOf(d);

				if (index >= 0) {
					keys.splice(index, 1);
				}

				keys.unshift(d);

				uni.setStorageSync('jd-searchKey', keys);
			}

			this.$emit('change', d);
			this.$emit('input', d);
			uni.hideKeyboard()

			this.$nextTick(() => {
				this.showList = false;
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.jd-search__wrap {
	.jd-search {
		display: flex;
		align-items: center;
		height: 80rpx;
		padding: 20rpx 10rpx 10rpx 30rpx;

		ui-input {
			flex: 1;
		}

		/deep/.ui-input {
			flex: 1;
			background-color: #f7f8fa !important;
			border: 1rpx solid $main-color;
			border-radius: 70rpx;

			&__inner {
				background-color: #f7f8fa;
			}
		}

		button {
			background-color: #fff;
			font-size: 26rpx;
			color: $main-color;
			margin: 0 20rpx;

			&::after {
				border: 0;
			}

			&:active {
				background-color: #f7f7f7;
			}
		}
	}

	.jd-search__mask {
		position: fixed;
		left: 0;
		top: 100rpx;
		background-color: #fff;
		height: calc(100% - 100rpx);
		width: 100%;
		z-index: 9;
		overflow: hidden auto;

		.block {
			height: 80rpx;
			line-height: 80rpx;
			margin: 0 40rpx;
			font-size: 28rpx;
			border-bottom: 1rpx solid #eee;

			&:active {
				opacity: 0.7;
			}
		}
	}
}
</style>
